
package com.savi.myapplication.fragment;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;

import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.savi.myapplication.BaseActivity;
import com.savi.myapplication.FlyCardActivity;
import com.savi.myapplication.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class LongEnduranceCardFragment extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";


    private String mParam1;
    private String mParam2;

    static String pdfFilePath = null;

    private FlyCardActivity flyCardActivity ;
    public LongEnduranceCardFragment() {
        // Required empty public constructor
    }


    public static LongEnduranceCardFragment newInstance(String param1, String param2) {
        LongEnduranceCardFragment fragment = new LongEnduranceCardFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    /**
     * 获取数据
     */
    public Map<String, String> getData(Activity activity) {
        Map<String, String> dataMap = new HashMap<>();
        for (int i = 0; i <= 83; i++) {
            String viewIdName = "fill_" + i;
            int resId = activity.getResources().getIdentifier(viewIdName, "id", activity.getPackageName());
            TextView textView = activity.findViewById(resId);
            if (textView != null) {
                String value = textView.getText().toString();
                dataMap.put(viewIdName, value);
            }
        }
        return dataMap;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_long_endurance_card, container, false);
        flyCardActivity =  (FlyCardActivity) FlyCardActivity.getActivity();
        Button buttonGeneratePDF = view.findViewById(R.id.buttonGeneratePDF);
        buttonGeneratePDF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    // 传入Fragment的context
                    generateTempPDF(getContext());
                    Toast.makeText(getContext(), "PDF生成成功！", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Button buttonPreviewPDF = view.findViewById(R.id.buttonPreviewPDF);

        buttonPreviewPDF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                previewPDF(getContext(),pdfFilePath);
                // 这里可以继续调用你的PDF预览方法
            }
        });

        return view;
    }

    /**
     * 填充模板中的数据
     */
    public  void fillData(AcroFields fields, Map<String, String> data) {
        try {
            for (String key : data.keySet()) {
                String value = data.get(key);
                // 为字段赋值,注意字段名称是区分大小写的
                fields.setField(key, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 添加预览PDF的方法
    public void previewPDF(Context context, String pdfFilePath) {
        File pdfFile = new File(pdfFilePath);  // 传入最新生成的文件路径
        if (pdfFile.exists()) {
            Uri pdfUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", pdfFile);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(pdfUri, "application/pdf");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            try {
                context.startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(context, "没有找到可以打开 PDF 的应用", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(context, "PDF 文件不存在，请先生成 PDF", Toast.LENGTH_SHORT).show();
        }
    }

    public String generateTempPDF(Context context) throws Exception {
        PdfReader reader = null;
        PdfStamper ps = null;
        OutputStream fos = null;
        ByteArrayOutputStream bos = null;
        InputStream is = null;
        try {
            // 获取外部存储的根目录
            File externalStorage = Environment.getExternalStorageDirectory();

            // 构建具体的文件路径
            File file = new File(externalStorage, "MFBdata/Template/LongEnduranceCardPDF.pdf");

            // 检查文件是否存在
            if (file.exists()) {
                // 如果文件存在，使用 FileInputStream 读取文件
                is = new FileInputStream(file);
                Log.d("FileSuccess", "模板文件已找到: " + file.getAbsolutePath());
            } else {
                // 如果文件不存在，提示未发现模板文件
                Log.e("FileError", "未发现模板文件: " + file.getAbsolutePath());
                Toast.makeText(context, "未发现模板文件", Toast.LENGTH_SHORT).show();
            }

            reader = new PdfReader(is);
            bos = new ByteArrayOutputStream();
            ps = new PdfStamper(reader, bos);

            // 使用中文字体
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

            ArrayList<BaseFont> fontList = new ArrayList<>();
            fontList.add(bf);

            AcroFields fields = ps.getAcroFields();
            fields.setSubstitutionFonts(fontList);
            // 设置表单字段字体大小及其他样式
            for (String fieldName : fields.getFields().keySet()) {
                fields.setFieldProperty(fieldName, "textfont", bf, null);  // 设置中文字体
                fields.setFieldProperty(fieldName, "textsize", 12f, null);  // 设置字体大小为12
            }

            Map<String, String> data = getData(flyCardActivity);
            fillData(fields, data); // 渲染数据

            // 必须调用这个，否则文档不会生成
            ps.setFormFlattening(true);
            ps.close();

            // 获取当前日期作为文件夹名称
            String currentDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());

            // 获取当前时间戳作为文件名
            String timeStamp = String.valueOf(System.currentTimeMillis());

            // 构建你要保存的目录路径
            File dir = new File(externalStorage, "MFBdata/LongEnduranceCard");
            if (!dir.exists()) {
                dir.mkdirs();  // 创建日期文件夹
            }

            // 生成 PDF 文件的路径
            pdfFilePath = dir.getAbsolutePath() + "/" + timeStamp + ".pdf";

            // 写入 PDF 文件
            fos = new FileOutputStream(pdfFilePath);
            fos.write(bos.toByteArray());

            Log.d("PDFGeneration", "PDF 生成成功: " + pdfFilePath);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                fos.close();
            }
            if (bos != null) {
                bos.close();
            }
            if (reader != null) {
                reader.close();
            }
            if (is != null) {
                is.close();
            }
        }

        return pdfFilePath;  // 返回生成的 PDF 文件路径
    }
}